<template>
  <view class="container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input
          class="search-input"
          type="text"
          v-model="searchQuery"
          placeholder="搜索商品"
          @confirm="handleSearch"
          confirm-type="search"
        />
        <uni-icons
          v-if="searchQuery"
          type="clear"
          size="16"
          color="#999"
          @click="clearSearch"
        ></uni-icons>
      </view>
    </view>

    <!-- 分类筛选 -->
    <scroll-view
      scroll-x
      class="category-filter"
      :scroll-with-animation="true"
      :show-scrollbar="false"
      :refresher-enabled="false"
    >
      <view
        class="filter-item"
        :class="{ active: currentCategory === 'all' }"
        @click="selectCategory('all')"
      >
        全部
      </view>
      <template v-for="category in categories" :key="category.id">
        <view
          class="filter-item"
          :class="{ active: currentCategory === category.id }"
          @click="selectCategory(category.id)"
        >
          <text>{{ category.name }}</text>
        </view>
        <view
          v-for="subCategory in category.children"
          :key="subCategory.id"
          class="filter-item sub-category"
          :class="{ active: currentCategory === subCategory.id }"
          @click="selectCategory(subCategory.id)"
        >
          <text>{{ subCategory.name }}</text>
        </view>
      </template>
    </scroll-view>

    <!-- 商品列表 -->
    <scroll-view
      scroll-y
      class="product-list"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      @refresherrefresh="onRefresh"
      :refresher-triggered="isRefreshing"
      :show-scrollbar="false"
    >
      <view v-if="products.length === 0" class="empty-state">
        <image src="/static/empty.png" mode="aspectFit" class="empty-image" />
        <text class="empty-text">暂无商品</text>
      </view>

      <view v-else class="products-container">
        <view
          v-for="product in products"
          :key="product.id"
          class="product-item"
          @click="navigateToDetail(product)"
        >
          <view class="product-item-content">
            <image
              class="product-image"
              :src="product.productDetail.mainImage"
              mode="aspectFill"
              lazy-load
            />
            <view class="product-info">
              <text class="product-name">{{ product.name }}</text>
              <view class="product-price-row">
                <text class="product-price">¥{{ product.price }}</text>
                <text
                  class="product-original-price"
                  v-if="product.originalPrice"
                  >¥{{ product.originalPrice }}</text
                >
              </view>
              <view class="product-meta">
                <text class="product-sales">销量: {{ product.sales }}</text>
                <text v-if="product.isHot" class="hot-tag">热销</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <view v-if="hasMore" class="loading-more">
        <text class="loading-text">加载中...</text>
      </view>
      <view v-else-if="products.length > 0" class="no-more">
        <text class="no-more-text">没有更多了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import http from "@/utils/request";

interface Product {
  id: number;
  productNo: string;
  name: string;
  price: number;
  originalPrice: number;
  brandId: number;
  categoryId: number;
  status: number;
  sort: number;
  description: string;
  mainImage: string;
  subImages: string[];
  volume: number;
  unitId: number;
  unitSymbol: string;
  sales: number;
  isHot: number;
}

interface Category {
  id: number;
  name: string;
  parentId: number;
  parentName: string;
  level: number;
  icon: string;
  sort: number;
  status: number;
  statusName: string;
  children?: Category[];
}

const searchQuery = ref("");
const currentCategory = ref<string | number>("all");
const page = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const isRefreshing = ref(false);

// 分类数据
const categories = ref<Category[]>([]);

// 商品数据
const products = ref<Product[]>([]);

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await http.get("/product/api/category/tree");
    categories.value = res.data;
  } catch (error) {
    console.error("获取分类失败：", error);
    uni.showToast({
      title: "获取分类失败，请稍后重试",
      icon: "none",
    });
  }
};

// 获取商品列表
const fetchProducts = async (isLoadMore = false) => {
  if (!isLoadMore) {
    page.value = 1;
    hasMore.value = true;
  }

  if (!hasMore.value) return;

  try {
    const params = {
      pageNum: page.value,
      pageSize: pageSize.value,
      ...(currentCategory.value !== "all"
        ? { categoryId: currentCategory.value }
        : {}),
      ...(searchQuery.value ? { keyword: searchQuery.value } : {}),
    };

    const res = await http.get("/product/api/product/list", params);

    if (!res || res.code !== 200) {
      console.error("接口返回数据格式错误:", res);
      uni.showToast({
        title: res?.msg || "获取商品列表失败，请稍后重试",
        icon: "none",
      });
      products.value = [];
      hasMore.value = false;
      return;
    }

    const { rows = [], total = 0 } = res;

    if (isLoadMore) {
      products.value = [...products.value, ...rows];
    } else {
      products.value = rows;
    }

    hasMore.value = products.value.length < total;
    page.value++;
  } catch (error) {
    console.error("获取商品列表失败：", error);
    uni.showToast({
      title: "获取商品列表失败，请稍后重试",
      icon: "none",
    });
    products.value = [];
    hasMore.value = false;
  } finally {
    isRefreshing.value = false;
  }
};

// 清除搜索
const clearSearch = () => {
  searchQuery.value = "";
  fetchProducts();
};

// 搜索处理
const handleSearch = () => {
  if (!searchQuery.value.trim()) {
    uni.showToast({
      title: "请输入搜索关键词",
      icon: "none",
    });
    return;
  }
  fetchProducts();
};

// 选择分类
const selectCategory = (categoryId: string | number) => {
  currentCategory.value = categoryId;
  fetchProducts();
};

// 加载更多
const loadMore = () => {
  if (hasMore.value) {
    fetchProducts(true);
  }
};

// 跳转到商品详情
const navigateToDetail = (product: Product) => {
  uni.navigateTo({
    url: `/pages/product/detail?id=${product.id}`,
  });
};

// 下拉刷新
const onRefresh = async () => {
  isRefreshing.value = true;
  await fetchProducts();
};

onMounted(() => {
  Promise.all([fetchCategories(), fetchProducts()]);
});
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

.search-bar {
  padding: 10px 15px;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  padding: 8px 15px;
  border-radius: 20px;
}

.search-input {
  flex: 1;
  font-size: 14px;
  margin: 0 8px;
}

.category-filter {
  white-space: nowrap;
  background-color: #fff;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 60px;
  z-index: 99;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.filter-item {
  display: inline-flex;
  align-items: center;
  padding: 8px 16px;
  margin: 0 6px;
  font-size: 14px;
  color: #666;
  border-radius: 20px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  background-color: #f8f8f8;
  border: 1px solid transparent;
}

.filter-item:active {
  transform: scale(0.95);
}

.filter-item.active {
  background-color: #007aff;
  color: #fff;
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.2);
  border-color: #007aff;
}

.filter-item.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 3px;
  background-color: #fff;
  border-radius: 2px;
}

.filter-item.sub-category {
  background-color: #f5f5f5;
  margin-left: 15px;
  font-size: 13px;
  padding: 6px 14px;
  border: 1px solid #eee;
}

.filter-item.sub-category.active {
  background-color: #e6f2ff;
  color: #007aff;
  border-color: #007aff;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.1);
}

.filter-item.sub-category.active::after {
  background-color: #007aff;
}

.product-list {
  flex: 1;
  padding: 10px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.empty-image {
  width: 120px;
  height: 120px;
  margin-bottom: 10px;
}

.empty-text {
  color: #999;
  font-size: 14px;
}

.products-container {
  display: flex;
  flex-wrap: wrap;
  margin: -5px;
}

.product-item {
  width: 50%;
  padding: 5px;
  box-sizing: border-box;
}

.product-item-content {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  height: 100%;
  transition: transform 0.2s ease;
  position: relative;
}

.product-item-content:active {
  transform: scale(0.98);
}

.product-image {
  width: 100%;
  height: 60%;
  display: block;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  background-color: #f5f5f5;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
}

.product-info {
  flex: 1;
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin-top: 100%;
}

.product-name {
  font-size: 14px;
  color: #333;
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  height: 40px;
}

.product-price-row {
  display: flex;
  align-items: baseline;
  margin-bottom: 5px;
}

.product-price {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: bold;
  margin-right: 4px;
}

.product-original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.hot-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #fff1f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  font-size: 12px;
}

.loading-more {
  text-align: center;
  padding: 15px 0;
}

.loading-text {
  font-size: 14px;
  color: #999;
}

.no-more {
  text-align: center;
  padding: 15px 0;
}

.no-more-text {
  font-size: 14px;
  color: #999;
}
</style>
